﻿using MockJson.Database;
using MockJson.Properties;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MockJson
{
    public static class App
    {

        static Lazy<IFreeSql> sqliteLazy = new Lazy<IFreeSql>(() => new FreeSql.FreeSqlBuilder()
         .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=MockJson.db")
         .UseMonitorCommand(cmd => Console.WriteLine($"Sql：{cmd.CommandText}"))//监听SQL语句
         .UseAutoSyncStructure(true) //自动同步实体结构到数据库，FreeSql不会扫描程序集，只有CRUD时才会生成表。
         .Build());
        public static IFreeSql DB => sqliteLazy.Value;



        public static string GetValue(string key, string defaultValue, List<Setting> settings)
        {
            if (settings == null)
            {
                settings = DB.Queryable<Setting>().ToList();
            }

            if (settings != null)
            {
                var setting = settings.FirstOrDefault(x => x.Key == key);
                if (setting != null)
                    return setting.Value;
                else
                    return defaultValue;
            }
            return defaultValue;
        }

        public static void WriteValue(string key, string value)
        {
            var setting = DB.Select<Setting>().Where(x => x.Key == key).First();
            if (setting == null)
            {
                setting = new Setting
                {
                    Key = key,
                    Value = value
                };

                DB.Insert(setting).ExecuteAffrows();
            }
            else
            {
                setting.Value = value;
                DB.Update<Setting>().SetSource(setting).ExecuteAffrows();
            }
        }


        public static void WriteDefaultSetting()
        {
            var settings = DB.Select<Setting>().ToList();
            WriteSettingValue("IP", "localhost", settings);
            WriteSettingValue("PORT", "8099", settings);
            WriteSettingValue("AUTOSTART", "0", settings);
        }

        private static void WriteSettingValue(string key, string value, List<Setting> settings)
        {
            var setting = settings.FirstOrDefault(x => x.Key == key);
            if (setting == null)
            {
                setting = new Setting
                {
                    Key = key,
                    Value = value
                };
                DB.Insert(setting).ExecuteAffrows();
            }
        }
    }
}
